package com.acooly.module.openapi.client.provider.allinpay.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64InputStream;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @Auther: zhike
 * @Date: 2018/8/30 14:29
 * @Description:
 */
@Slf4j
public class FileUtils {

    /**
     * 生成对账文件
     *
     * @param billContext
     */
    public static void witeBill(String billContext,String filePath,String billData) {
        FileOutputStream sos = null;
        ZipInputStream zin = null;
        FileOutputStream os = null;
        try {
            String fileName = billData+".zip";
            File billFile = new File(filePath + File.separator + fileName);
            if (!billFile.exists()) {
                billFile.getParentFile().mkdirs();
            }
            //写文件
            sos = new FileOutputStream(billFile);
            Base64InputStream b64is = new Base64InputStream(IOUtils.toInputStream(billContext, "GBK"), false);
            IOUtils.copy(b64is, sos);
            IOUtils.closeQuietly(b64is);
            //解压
            zin = new ZipInputStream(new FileInputStream(billFile));
            ZipEntry zipEntry = null;
            while ((zipEntry = zin.getNextEntry()) != null) {
                String entryName = zipEntry.getName();
                os = new FileOutputStream(filePath + "/" + entryName);
                byte[] buf = new byte[1024];
                int len;
                while ((len = zin.read(buf)) > 0) {
                    os.write(buf, 0, len);
                }
            }
            log.info("对账文件下载成功");
        } catch (Exception e) {
            log.error("对账文件生成失败：{}", e.getMessage());
        } finally {
            try {
                sos.close();
                os.close();
                zin.closeEntry();
            } catch (Exception e) {
                log.info("输出流关闭失败:{}", e.getMessage());
            }
        }
    }
}
